<script setup lang="ts">
import {onMounted, ref, toRaw, computed} from "vue";
import axios from "axios";
import {ElNotification} from "element-plus";
import {ServerHost, loginUser} from "@/main.js";
import {Refresh, Search, Timer, Upload} from "@element-plus/icons-vue";
import dayjs from 'dayjs'
import PostOrEditPolicy from "@/components/policyManage/PostOrEditPolicy.vue";
import Color from 'color';
import PostOrEditGoods from "@/components/goodsManage/PostOrEditGoods.vue";

const sellerGoodsList = ref([])
const isLoadingList = ref(true)
const isEditDialogVisible = ref(false)
const selectedGoods = ref()

// 懒加载商家产品列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const goodsTypeList = ref([{}])
const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary')
const loadList = () => {
  console.log("开始获取商品列表")
  axios.get(`${ServerHost}/getSellerGoodsList?sellerId=${loginUser.value.id}`)
      .then((res) => {
            if (res.status === 200) {
              sellerGoodsList.value = res.data;
              // 获取所有商品类型
              goodsTypeList.value = []
              sellerGoodsList.value.forEach((goods: { type: string }) => {
                    if (goodsTypeList.value.find((type: { name: string }) => type.name === goods.type) === undefined)
                      if (goods.type != undefined)
                        goodsTypeList.value.push({name: goods.type})
                  }
              )
              if (goodsTypeList.value.length > 0) {
                const primaryColorHSL = Color(primaryColor).hsl()
                // 0 - 180 平均分配
                const a = (180 - 0) / (goodsTypeList.value.length - 1)
                primaryColorHSL.color[0] = -a
                goodsTypeList.value.forEach((type: string) => {
                  primaryColorHSL.color[0] += a
                  type.color = primaryColorHSL.string()
                })
              }
              ElNotification({
                title: '商品获取成功',
                type: 'success',
                position: 'bottom-right',
              })
              hasLoad.value = true
              isLoadingList.value = false
            } else {
              ElNotification({
                title: '商品获取失败',
                type: 'error',
                position: 'bottom-right',
              })
            }
          }
      )
}

const filterTableData = computed(() =>
    sellerGoodsList.value.filter(goods => {
      return goods.name.includes(searchKey.value) ||
          goods.id.includes(searchKey.value)
    })
)

// const onEditPolicy = (id: string) => {
//   console.log(id)
// }

const onRowClick = (row: any, column: any, event: Event) => {
  isEditDialogVisible.value = true

  // selectedPolicy.value = policyList.value.find((Policy: any) => {
  //   return Policy.id === row.id
  // })
  sellerGoodsList.value.forEach((policy: any) => {
    if (policy.id === row.id) {
      // 深拷贝policy，防止子组件修改父组件数据
      selectedGoods.value = structuredClone(toRaw(policy))
      console.log(selectedGoods.value)
    }
  })
}

// watch(policyList, (newValue, oldValue) => {
//   console.log("数据变化了", newValue, oldValue);
// }, { deep: true });


const getIsSubmitDone = (value: string) => {
  isEditDialogVisible.value = !value
  loadList()
}

const searchKey = ref("")

const onSearchKeydown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    // onSearch()
  }
}

const onSearch = () => {
  if (searchKey.value !== "") {
    // loadList()
  }
}

const onClearSearch = (id: string) => {
  // loadList()
}

const isAddDialogVisible = ref(false)


</script>

<template>
  <div ref="observerDiv"/>
  <!--  忽略warn type="search" -->
  <div class="flex">
    <el-input type="text" v-model="searchKey" @keydown="onSearchKeydown" class="mb-2 mr-3"
              placeholder="输入名称、ID来搜索产品"
              :prefix-icon="Search" clearable @clear="onClearSearch">
      <template #append>
        <el-button :icon="Search" @click="onSearch"/>
      </template>
    </el-input>

    <el-button @click="isAddDialogVisible = true">
      <el-icon class="el-icon--left">
        <Upload/>
      </el-icon>
      上架商品
    </el-button>

    <el-button @click="loadList">
      <el-icon class="el-icon--left">
        <Refresh/>
      </el-icon>
      刷新列表
    </el-button>
  </div>

  <el-tag class="w-full">点击产品以编辑</el-tag>
  <!--  Table-->
  <!-- height: 减去导航栏、页脚、搜索栏等元素的高度 -->
  <el-table
      :data="filterTableData"
      height="calc(100vh - 120px - 140px)"
      empty-text="没有产品"
      v-loading="isLoadingList"
      :onRowClick="onRowClick">
    <el-table-column
        prop="id"
        label="产品ID"
    >
      <template #default="row">
        <p class="goods-id">{{ row.row.id.split('-')[4] }}</p>
      </template>
    </el-table-column>
    <el-table-column
        prop="name"
        label="名称"
    />
    <el-table-column
        prop="type"
        label="类型"
    >
      <template #default="row">
        <el-button plain :hit="false" :color="goodsTypeList.find((type) => type.name === row.row.type)?.color">
          {{ row.row.type }}
        </el-button>
      </template>
    </el-table-column>
    <el-table-column
        prop="priceCent"
        label="售价(￥)"
        align="right"
        sortable
    >
      <template #default="row">
        <p>{{ (row.row.priceCent / 100).toFixed(2) }}</p>
      </template>
    </el-table-column>

    <el-table-column
        prop="inventory"
        label="库存"
        align="right"
        sortable
    />
    <el-table-column
        prop="sales"
        label="销量"
        align="right"
        sortable
    />
  </el-table>

  <!-- Edit Dialog -->
  <el-dialog
      v-model="isEditDialogVisible"
      title="编辑商品"
      width="500">
    <PostOrEditGoods type="edit" @getValue="getIsSubmitDone" :goods="selectedGoods"
                     :key="selectedGoods"/>
  </el-dialog>

  <!-- Add Dialog -->
  <el-dialog
      v-model="isAddDialogVisible"
      title="上架商品"
      width="500">
    <PostOrEditGoods type="new"/>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-table .el-table.row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.goods-id {
  font-size: 0.7rem;
}
</style>
